<template>
  <div class="invite-code-management">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>管理员邀请码管理</span>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="generateNewCode">
          生成新邀请码
        </el-button>
      </div>

      <div v-loading="loading" class="code-container">
        <el-empty v-if="!inviteCodes.length" description="暂无邀请码"></el-empty>
        <el-card
          v-for="code in inviteCodes"
          :key="code.value"
          class="code-card"
          shadow="hover"
        >
          <div class="code-content">
            <span class="code-value">{{ code.value }}</span>
            <div class="code-actions">
              <el-button
                type="text"
                icon="el-icon-copy-document"
                @click="copyCode(code.value)"
              >
                复制
              </el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                class="delete-btn"
                @click="handleDeleteCode(code.value)"
              >
                删除
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 生成邀请码对话框 -->
    <el-dialog
      title="生成管理员邀请码"
      :visible.sync="generateDialogVisible"
      width="500px">
      <el-form
        ref="codeForm"
        :model="codeForm"
        :rules="codeRules"
        label-width="100px">
        <el-form-item label="生成数量" prop="count">
          <el-input-number
            v-model="codeForm.count"
            :min="1"
            :max="10">
          </el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="generateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGenerateForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from '@/utils/http';

export default {
  name: 'InviteCodeManagement',
  data() {
    return {
      loading: false,
      inviteCodes: [],
      generateDialogVisible: false,
      codeForm: {
        count: 1
      },
      codeRules: {
        count: [
          { required: true, message: '请输入生成数量', trigger: 'blur' }
        ]
      },
      submitting: false
    };
  },

  created() {
    this.fetchInviteCodes();
  },

  methods: {
    // 获取邀请码列表
    async fetchInviteCodes() {
      this.loading = true;
      try {
        const res = await httpInstance.post('api/sys/getCode/');

        if (res.code === 200) {
          // 将返回的字符串数组转换为对象数组
          this.inviteCodes = res.data.map(code => ({
            value: code
          }));
          console.log('获取到的邀请码:', this.inviteCodes); // 添加调试日志
        } else {
          this.$message.error(res.msg || '获取邀请码列表失败');
        }
      } catch (error) {
        console.error('获取邀请码列表失败:', error);
        this.$message.error('获取邀请码列表失败');
      } finally {
        this.loading = false;
      }
    },

    // 复制邀请码
    copyCode(code) {
      const textarea = document.createElement('textarea');
      textarea.value = code;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      this.$message.success('邀请码已复制到剪贴板');
    },

    // 显示生成邀请码对话框
    generateNewCode() {
      this.generateDialogVisible = true;
      this.codeForm = {
        count: 1
      };
      this.$nextTick(() => {
        this.$refs.codeForm && this.$refs.codeForm.resetFields();
      });
    },

    // 提交生成邀请码表单
    submitGenerateForm() {
      this.$refs.codeForm.validate(async (valid) => {
        if (!valid) return;

        this.submitting = true;
        try {
          const res = await httpInstance.post('/api/sys/genCode/' + this.codeForm.count);
          if (res.code === 200) {
            this.$message.success(`成功生成 ${this.codeForm.count} 个邀请码`);
            this.generateDialogVisible = false;
            this.fetchInviteCodes();
          } else {
            this.$message.error(res.msg || '生成邀请码失败');
          }
        } catch (error) {
          console.error('生成邀请码失败:', error);
          this.$message.error('生成邀请码失败');
        } finally {
          this.submitting = false;
        }
      });
    },

    // 处理删除邀请码
    async handleDeleteCode(code) {
      try {
        await this.$confirm('确定要删除该邀请码吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const res = await httpInstance.post(`/api/sys/delCode/${code}`);

        if (res.code === 200) {
          this.$message.success('删除成功');
          // 重新获取邀请码列表
          this.fetchInviteCodes();
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除邀请码失败:', error);
          this.$message.error('删除失败');
        }
      }
    }
  }
};
</script>

<style scoped>
.invite-code-management {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.code-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
  padding: 16px;
}

.code-card {
  transition: all 0.3s;
}

.code-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.code-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
}

.code-value {
  font-family: monospace;
  font-size: 16px;
  color: #606266;
}

.code-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}
</style>
```
